<?php


namespace app\api\controller\v32;


use app\api\controller\v13\Auth2;
use app\common\cachemodel\ArticleComment;
use app\common\cachemodel\ArticleCommentGood;
use app\common\cachemodel\ArticleCommentReply;
use app\common\cachemodel\Goods;
use app\common\cachemodel\zlcr2\Zlcr2QuestionUserView;
use app\common\cachemodel\zlcr2\Zlcr2UserAddQuestion;
use app\common\cachemodel\zlcr2\Zlcr2UserQuestion;
use app\common\cachemodel\zlcr3\Zlcr3ConsultAccount;
use app\common\cachemodel\ZlcrAstr;
use app\common\cachemodel\ZlUserVip;
use app\common\lib\ConfigManage;
use app\common\lib\Util;
use app\common\model\MessageCenter;
use app\common\model\Recode;
use app\common\model\Slide;
use app\common\model\User;
use XznsTools\cache\CacheManage;

class QuestionAnswer extends Auth2
{
    /**
     * 问答首页
     */
    public function index()
    {
        $page = input('page/d', 1);

        $resBannerList = [];
        if ($page === 1)
        {
            // 获取猜你想问
            $guessQuestionList = (new \app\common\cachemodel\zlcr2\GuessQuestion())->getDataList();
            // 获取banner
            $bannerList = (new Slide())->getQuestionAnswerAdv();
            $bannerData = [];
            if (!empty($bannerList))
            {
                foreach ($bannerList as $item)
                {
//                    $guessQuestionList[] = [
//                        'text' => '',
//                        'tip' => '',
//                        'color' => '',
//                        'img' => $item['image'] ?? '',
//                        'target' => $item['target'],
//                        'link' => $item['link'],
//                        'type' => 2,   // 1=>猜你先问 2=>banner
//                    ];
                    $bannerData[] = [
                        'text' => '',
                        'tip' => '',
                        'color' => '',
                        'img' => $item['image'] ?? '',
                        'target' => $item['target'],
                        'link' => $item['link'],
                        'type' => 2,   // 1=>猜你先问 2=>banner
                    ];
                }
            }
//            $resBannerList = $guessQuestionList;
            // banner 数据强行挪动到最前面展示
            $resBannerList = array_merge($bannerData, $guessQuestionList);
        }

        $listData = (new Zlcr2UserQuestion())->getIndexList($this->user['id'] ?? 0, $page, 10, true);
        $replyNum = 0;
        $messageNum = 0;
        if ($this->user)
        {
            $ids = (new Zlcr2UserQuestion())->getUserUnReadIds($this->user['id']);//未读问题ids
            if ($ids)
            {
                $replyNum = 1;
            } else
            {
                $ids = (new Zlcr2QuestionUserView())->getUserUnReadViewIds($this->user['id']);//未读蹭看ids
                if ($ids)
                {
                    $replyNum = 1;
                }
            }
            $messageData = (new MessageCenter())->getUnreadMsgNum($this->user['id']);
            $messageNum = array_sum($messageData);
        }


        $resData = [
            'reply_num' => $replyNum,
            'message_num' => $messageNum,
            'list_data' => $listData,
            'banner_list' => $resBannerList
        ];


        return show(config('code.success'), '请求成功', $resData);

    }

    /**
     * 问答问题详情
     */
    public function questionDetail()
    {
        $qid = input('qid/s', '');
        $page = input('page/d', 1);

        $resData['question_info'] = null;
        $uid = $this->user ? $this->user['id'] : 0;

        $questionModel = new Zlcr2UserQuestion();
        $questionInfo = $questionModel->getInfoById($qid, ['id', 'astr_id', 'uid', 'question_type', 'question_extend', 'status', 'astr_receiving_time', 'question', 'question_des', 'consult_time', 'is_anonymity', 'answer_content', 'answer_duration', 'reply_time', 'question_imgs', 'comment_num', 'read_num', 'look_num', 'is_read', 'same_num', 'is_hide', 'delete_time']);
        if ($questionInfo['delete_time'] > 0)
        {
            CacheManage::getInstance()->setCacheConfig('question_answer.question')->delJudge($qid, 'time_sort');
            CacheManage::getInstance()->setCacheConfig('question_answer.question')->delJudge($qid, 'recommended_sort');
        }
        $anonymityNickname = '匿名用户';
        $anonymityAvatar = '/test/question_answer/anonymity1.png';
        if ($page === 1)
        {
            if (!$questionInfo)
            {
                return show(config('code.error'), '服务异常，问题不存在～');
            }
            //问题已读
            if ($uid && !$questionInfo['is_read'] && $uid === $questionInfo['uid'])
            {
                $questionModel->UpdateData($qid, ['is_read' => 1, 'uid' => $this->user['id']]);
            }

            $isSelf = $this->user && $questionInfo['uid'] === $uid;
            $userDes = '小行星神秘人';
            if ($questionInfo['is_anonymity'] !== 1)
            {
                $userInfo = (new User())->getUserinfo(['id' => $questionInfo['uid']]);
                if ($userInfo['rid'])
                {
                    $recode = (new Recode())->getRecode(['id' => $userInfo['rid']]);
                    if ($recode)
                    {
                        $utilModel = new Util();
                        $userDes = '日' . $utilModel->recodeAstroShorthand($recode['sun']) . '月' . $utilModel->recodeAstroShorthand($recode['moon']) . '升' . $utilModel->recodeAstroShorthand($recode['asc']);
                    }
                }
            }

            $questionData = null;
            switch ($questionInfo['question_type'])
            {
                case 1:
                    if ($isSelf)
                    {
                        $sexTxt = [
                            1 => '男',
                            2 => '女'
                        ];
                        if (isset($questionInfo['question_extend']['recode1']) && $questionInfo['question_extend']['recode1'])
                        {
                            $questionData['astro_data'][] = [
                                'nickname' => $questionInfo['question_extend']['recode1']['name'],
                                'avatar' => $questionInfo['question_extend']['recode1']['avatar'],
                                'sex' => $sexTxt[$questionInfo['question_extend']['recode1']['type']] ?? '未知',
                                'age' => Util::getAgeByBirth($questionInfo['question_extend']['recode1']['year'], $questionInfo['question_extend']['recode1']['month'], $questionInfo['question_extend']['recode1']['day'], 2),
                            ];
                        }
                        if (isset($questionInfo['question_extend']['recode2']) && $questionInfo['question_extend']['recode2'])
                        {
                            $questionData['astro_data'][] = [
                                'nickname' => $questionInfo['question_extend']['recode2']['name'],
                                'avatar' => $questionInfo['question_extend']['recode2']['avatar'],
                                'sex' => $sexTxt[$questionInfo['question_extend']['recode2']['type']] ?? '未知',
                                'age' => Util::getAgeByBirth($questionInfo['question_extend']['recode2']['year'], $questionInfo['question_extend']['recode2']['month'], $questionInfo['question_extend']['recode2']['day'], 2),
                            ];
                        }
                    }
                    break;
                case 2:
                case 3:
                    $questionData = $questionInfo['question_extend'];
                    break;
                default:
            }

            $answerData1 = null;
            $answerData2 = null;
            switch ($questionInfo['status'])
            {
                case 9:
                case 10:
                case 11:
                    $answerData2 = [
                        'tips' => '已取消悬赏问题'
                    ];
                    break;
                default:
                    if ($questionInfo['answer_content'])
                    {
                        /**
                         * 处理文案中出现\u0000（空格编码）导致前端仅展示一行的问题
                         *  根据你抽到的这组塔罗牌面分析，你能收到伦艺的 offer
                         *   进行json_encode后变成了\u0000
                         */
                        $questionInfo['answer_content'] = str_replace(' ', '', $questionInfo['answer_content']);
                        $astrInfo = (new ZlcrAstr())->getInfoById($questionInfo['astr_id'], ['nickname', 'avatar']);
                        $answerIsShow = false; // 答案是否展示
                        if ($this->user && ($isSelf || (new Zlcr2QuestionUserView())->getQuestionUserIsView($this->user['id'], $qid)))
                        {   // 如果已蹭看 或者是发布自己的问题
                            $answerIsShow = true;
                            $btnText = '查看全部';
                        } else
                        {
                            $goodInfo = (new Goods())->getInfoById(83);
                            $btnText = ((float)($goodInfo['now_prize'])) . '元蹭看全部';
                        }
                        $answerData1 = [
                            'nickname' => $astrInfo['nickname'],
                            'avatar' => $astrInfo['avatar'],
                            'answer_time' => Util::timeToStr($questionInfo['reply_time']),  // 回复时间
                            'content' => $answerIsShow ? $questionInfo['answer_content'] : '',
                            'duration' => $questionInfo['answer_duration'],
                            'view_num' => $questionInfo['look_num'],
                            'btn_text' => $btnText,
                            'target' => 'local',
                            'link' => 'question_answer_detail?qid=' . $qid . '&need_auth=0',
                            'add_question_num' => (new Zlcr2UserAddQuestion())->getQuestionAddQuestionNum($qid),
                            'type' => $answerIsShow ? 1 : 2,
                            'gid' => 83,
                            'astr_avatar_target' => (new Zlcr3ConsultAccount())->getAstrTargetLink($questionInfo['astr_id']),
                        ];
                    }
                    if (!$answerData1)
                    {
                        $answerData2 = [
                            'tips' => '咨询师暂无回复，请耐心等待～'
                        ];
                    }
            }
            if (!$questionInfo['delete_time'])
            {
                $questionModel->changeQuestionInfo($questionInfo, 1, 1);
            }

            $questionInfoResData = [
                'nickname' => isset($userInfo) ? $userInfo['nickname'] ?? '' : $anonymityNickname,
                'avatar' => isset($userInfo) ? $userInfo['avatar'] ?? '' : $anonymityAvatar,
                'create_time' => Util::timeToStr($questionInfo['consult_time']),  // 咨询时间
                'user_des' => $userDes,
                'question' => $questionInfo['question'],
                'question_des' => $questionInfo['question_des'],
                'question_type' => $questionInfo['question_type'],
                'question_data' => $questionData,
                'comment_num' => $questionInfo['comment_num'],
                'view_num' => $questionInfo['read_num'],
                'photo_list' => $questionInfo['question_imgs'],
                'isself' => $isSelf ? 1 : 0,
                'answer_data1' => $answerData1,
                'answer_data2' => $answerData2,
                'author_id' => $questionInfo['uid'], // 打点时使用的字段，提问者的用户ID
            ];

            //提问用户的头像框、徽章、标签（注意：匿名用户不展示）
            if ($questionInfo['is_anonymity'] !== 1)
            {
                $adorn = Util::getUserAdorn($questionInfo['uid']);
                $resData['question_info'] = array_merge($questionInfoResData, $adorn);
            } else
            {
                $resData['question_info'] = $questionInfoResData;
            }
        }

        $articleCommentModel = new ArticleComment();
        $articleCommentModel->isAnonymity = $questionInfo['is_anonymity'] === 1;
        // 获取用户评论列表信息
        $commentData = $articleCommentModel->getPageCommentList($uid, 4, $qid, 2, $page);

        $resData = array_merge($resData, $commentData);

        if ($commentData['total'] !== $questionInfo['comment_num'])
        {
            if ($page === 1)
            {
                $resData['question_info']['comment_num'] = $commentData['total'];
            }

            $questionModel->UpdateData($qid, ['comment_num' => $commentData['total']]);
        }

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 获取评论详情
     * @return \think\response\Json
     * @throws \app\common\lib\exception\ApiException
     */
    public function getCommentReplyList()
    {
        $commentId = input('cid/d', 0);
        $page = input('page/d', 1);
        $uid = $this->user ? $this->user['id'] : 0;
        if (!$commentId)
        {
            return show(config('code.error'), '请求异常');
        }
        // 评论详情
        $commentInfo = current((new ArticleComment())->batchGetInfo([$commentId], ['create_time', 'uid', 'goods', 'reply', 'content', 'aid']));
        if (!$commentInfo)
        {
            return show(config('code.error'), '数据不存在');
        }
        // 问题详情
        $questionModel = new Zlcr2UserQuestion();
        $questionInfo = $questionModel->getInfoById($commentInfo['aid'], ['uid', 'is_anonymity']);
        $anonymityNickname = '匿名用户';
        $anonymityAvatar = '/test/question_answer/anonymity1.png';

        $resData = [];
        if ($page === 1)
        {
            $userTag = 0;
            if ($questionInfo['uid'] === (int)$commentInfo['uid'])
            {
                $userTag = 1;
            }

            // 获取用户所有的评论点赞ID
            $goods = $uid ? (new ArticleCommentGood())->getGoodFromCache($uid, 1) : [];
            $isOwner = $commentInfo['uid'] == $uid ? 1 : 0; // 判断是否是本人
            if ($userTag === 1 && $questionInfo['is_anonymity'] === 1)
            {
                $nickname = $anonymityNickname;
                $avatar = $anonymityAvatar;
            } else
            {
                // 获取用户信息
                $userInfo = $isOwner ? $this->user : current((new User())->batchGetUserInfo([$commentInfo['uid']], ['nickname', 'avatar']));
                $nickname = $userInfo['nickname'] ?? '';
                $avatar = $userInfo['avatar'] ?? '匿名用户';
            }

            // 评论的点赞数量转换成int
            $commentInfo['goods'] = (int)$commentInfo['goods'];
            $adorn = Util::getUserAdorn($commentInfo['uid']);
            $resData['comment_info'] = [
                'id' => (int)$commentId,
                'avatar' => $avatar,
                'avatar_adorn' => ($userTag === 1 && $questionInfo['is_anonymity'] === 1) ? '' : $adorn['avatar_adorn'],
                'nickname' => $nickname,
                'create_time' => Util::timeToStr($commentInfo['create_time']),
                'content' => htmlspecialchars_decode($commentInfo['content']),
                'reply_num' => $commentInfo['reply'] > 0 ? (int)$commentInfo['reply'] : 0,
                'good_num' => $commentInfo['goods'] < 0 ? 0 : $commentInfo['goods'],
                'is_good' => in_array($commentId, $goods, false) ? 1 : 0,
                'vip' => (new ZlUserVip())->getUserVipLevel($commentInfo['uid']),
                'is_owner' => $isOwner,
                'user_tag' => $userTag ?? 0,
                'user_type' => (new ConfigManage())->innerUser((int)($commentInfo['uid'] ?? 0)), //获取内部官方用户
                'owner_id' => (int)($commentInfo['uid'] ?? 0), // 楼主ID，打点专用
            ];
        } else
        {
            $resData['comment_info'] = null;
        }
        $replyModel = new ArticleCommentReply();
        $replyModel->isAnonymity = $questionInfo['is_anonymity'] === 1;

        $pageData = $replyModel->getQuestionAnswerPageCommentReplyList($uid, (int)$commentInfo['uid'], (int)$questionInfo['uid'], $commentId, $page);

        $resData = array_merge($resData, $pageData);
        $resData['author_id'] = $questionInfo['uid'] ?? 0;
        return show(config('code.success'), '请求成功', $resData);
    }
}
